import { createStore } from 'vuex';
import axios from 'axios';

export default createStore({
  state: {
    accessToken: localStorage.getItem('accessToken') || '',
    refreshToken: localStorage.getItem('refreshToken') || ''
  },
  mutations: {
    setAccessToken(state, token) {
      state.accessToken = token;
      localStorage.setItem('accessToken', token);
    },
    setRefreshToken(state, token) {
      state.refreshToken = token;
      localStorage.setItem('refreshToken', token);
    }
  },
  actions: {
    async login({ commit }, credentials) {
      try {
        const formData = new FormData();
        formData.append('username', credentials.username);
        formData.append('password', credentials.password);
        
        const response = await axios.post('/wow/users/login', formData);
        commit('setAccessToken', response.data.accessToken);
        commit('setRefreshToken', response.data.refreshToken);
        return response.data;
      } catch (error) {
        // 修改这里：优先显示后端返回的错误信息
        const errorMessage = error.response.data ||
                           '登录失败';
        throw new Error(errorMessage); // 抛出包含具体错误信息的新错误
      }
    },
    async register({ commit }, userData) {
      const formData = new FormData();
        formData.append('username', userData.username);
        formData.append('password', userData.password);
      const response = await axios.post('/wow/users/register', formData);
      return response.data;
    }
  }
});